package com.dayatang.product.webapp.action.role;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.dayatang.product.domain.Permission;
import com.dayatang.product.domain.Role;
import com.dayatang.product.domain.RolePermission;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.action.common.TreeJson;

/**
 * 文件名:RolePermissionJsonDataAction.java
 * 描述:角色权限json数据
 * 创建时间:2012-7-3 下午10:26:04
 * 创建者:mluo
 * 版本号:v2.0
 */
@ParentPackage(value = "web")
public class RolePermissionJsonDataAction extends BaseAction {

	private static final long serialVersionUID = -1108136653670125453L;

	private Role role;
	private List<TreeJson> results;
	
	@Action(results = {@Result(name = "success", type = "json")})
	public String execute() throws Exception {
		getAllData();
		role = Role.get(Role.class, role.getId());
		List<RolePermission> rolePermissions = RolePermission.findByRole(role);
		if (rolePermissions.size() > 0) {
			for (RolePermission rolePermission : rolePermissions) {
				for (TreeJson treeJson : results) {
					if (rolePermission.getPermission().getId() == treeJson.getId()) {
						treeJson.setChecked(true);
					}
				}
			}
		}
		return SUCCESS;
	}
	
	private void getAllData() {
		results = new ArrayList<TreeJson>();
		for (Permission permission : Permission.getMenuPermissions()) {
			TreeJson treeJson = new TreeJson();
			treeJson.setId(permission.getId());
			treeJson.setpId(0);
			treeJson.setName(permission.getDescription());
			treeJson.setOpen(true);
			results.add(treeJson);
			if (permission.getChildren().size() > 0) {
				getChildPermission(permission,permission.getChildren(),results);
			}
		}
	}
	
	private void getChildPermission(Permission parent, List<Permission> childPermissions, List<TreeJson> results) {
		for (Permission child : childPermissions) {
			TreeJson treeJson = new TreeJson();
			treeJson.setId(child.getId());
			treeJson.setpId(parent.getId());
			treeJson.setName(child.getDescription());
			results.add(treeJson);
			if (child.getChildren().size() > 0) {
				getChildPermission(child,child.getChildren(),results);
			}
		}
	}
	
	public void setRole(Role role) {
		this.role = role;
	}

	public List<TreeJson> getResults() {
		return results;
	}
	
}
